#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tornado
import tornado.web
import datetime
import os
import json
from config import etc
from controls import data_user_brief_mysql
from controls import data_user_buddy_mysql
from utils import log
from utils.session_base import ApiHost, ApiGuest
from utils.session_mc import BaseHandler


class FollowHandler(BaseHandler):
    @ApiHost
    def post(self, *args, **kwargs):
        current_userid = self.current_user.get('userid', None)
        userid = self.ss_params.get('userid', None)
        if not (current_userid and userid):
            log.w('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

        if userid == current_userid:
            log.w('can not follow yourself')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':'不能关注自己', 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

        isfollow = data_user_buddy_mysql.validate_follow_by_userid_fuserid(current_userid, userid)

        if isfollow == 0:
            item = {
                'userid': userid,
                'fanuserid': current_userid,
            }
            if data_user_buddy_mysql.add_user_buddy_item(item):
                res = {'idx':self.ss_idx, 'ret':0, 'msg':'关注成功', 'res':{'type': 1}}
                self.write(json.dumps(res))
                self.finish()
                return
            else:
                res = {'idx':self.ss_idx, 'ret':1, 'msg':'关注失败', 'res':{}}
                self.write(json.dumps(res))
                self.finish()
                return

        elif isfollow == 2:
            item = {
                'userid': userid,
                'fanuserid': current_userid,
            }
            if data_user_buddy_mysql.add_user_buddy_item(item):
                res = {'idx':self.ss_idx, 'ret':0, 'msg':'关注成功', 'res':{'type': 3}}
                self.write(json.dumps(res))
                self.finish()
                return
            else:
                res = {'idx':self.ss_idx, 'ret':1, 'msg':'关注失败', 'res':{}}
                self.write(json.dumps(res))
                self.finish()
                return
        elif isfollow == 1 or isfollow == 3:
            log.w('already follow')
            res = {'idx':self.ss_idx, 'ret':0, 'msg':'已经关注', 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

class UnfollowHandler(BaseHandler):
    @ApiHost
    def post(self, *args, **kwargs):
        current_userid = self.current_user.get('userid', None)
        userid = self.ss_params.get('userid', None)
        if not (userid and current_userid):
            log.w('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

        if userid == current_userid:
            log.w('can not unfollow yourself')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':'不能取消关注自己', 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

        isfollowed = data_user_buddy_mysql.validate_follow_by_userid_fuserid(current_userid, userid)

        if isfollowed ==0 or isfollowed == 2:
            log.w('not follow')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':'未关注', 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return
        elif isfollowed == 1:
            item = data_user_buddy_mysql.update_unfollow_by_userid_isfollow(userid, current_userid)
            if item:
                res = {'idx':self.ss_idx, 'ret':0, 'msg':'取消成功', 'res':{'type': 0}}
                self.write(json.dumps(res))
                self.finish()
                return
            else:
                res = {'idx':self.ss_idx, 'ret':1, 'msg':'取消失败', 'res':{}}
                self.write(json.dumps(res))
                self.finish()
                return
        elif isfollowed == 3:
            item = data_user_buddy_mysql.update_unfollow_by_userid_isfollow(userid, current_userid)
            if item:
                res = {'idx':self.ss_idx, 'ret':0, 'msg':'取消成功', 'res':{'type': 2}}
                self.write(json.dumps(res))
                self.finish()
                return
            else:
                res = {'idx':self.ss_idx, 'ret':1, 'msg':'取消失败', 'res':{}}
                self.write(json.dumps(res))
                self.finish()
                return

class GetFollowHandler(BaseHandler):
    @ApiGuest
    def post(self, *args, **kwargs):
        begin = self.ss_params.get('begin', None)
        limit = self.ss_params.get('limit', None)
        if begin and limit is None:
            log.i('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return
        if self.current_user:
            current_userid = self.current_user.get('userid', None)
        else:
            current_userid = None
        # log.i('----------------current_userid: %d ------------------' % current_userid)
        userid = self.ss_params.get('userid', None)
        # log.i('----------------userid: %d ------------------' % userid)
        if not userid:
            log.w('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

        current_userid_follow_list = data_user_buddy_mysql.get_user_follow_by_userid(current_userid, begin, limit)
        log.i('======== current_userid_follow_list: %s' % current_userid_follow_list)

        if current_userid_follow_list is None:
            current_userid_follow_list = []
        current_userid_fans_list = data_user_buddy_mysql.get_user_fans_by_userid(current_userid, begin, limit)
        if current_userid_fans_list is None:
            current_userid_fans_list = []
        current_userid_friends_list = list(set(current_userid_follow_list).intersection(set(current_userid_fans_list)))

        log.i('======== current_userid_fans_list: %s' % current_userid_fans_list)
        log.i('======== current_userid_friends_list: %s' % current_userid_friends_list)

        if userid is current_userid:
            if current_userid_follow_list == []:
                res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res': 0}
                self.write(json.dumps(res))
                self.finish()
                return
            current_user_follow_brief_list = data_user_brief_mysql.get_user_brief_by_userid_list(current_userid_follow_list)
            for item in current_user_follow_brief_list:
                item['thumblink'] = item['imglink'][0:-1] + u'132'
                if item['userid'] in current_userid_friends_list:
                    item['type'] = 3
                else:
                    item['type'] = 1

            res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':current_user_follow_brief_list}
            self.write(json.dumps(res))
            self.finish()
            return

        elif userid is not current_userid:
            follow_userid_list = data_user_buddy_mysql.get_user_follow_by_userid(userid, begin, limit)
            log.i('========follow_userid_list: %s' % follow_userid_list)
            if follow_userid_list is None:
                res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res': 0}
                self.write(json.dumps(res))
                self.finish()
                return
            follow_user_brief_list = data_user_brief_mysql.get_user_brief_by_userid_list(follow_userid_list)
            log.i('========follow_user_brief_list: %s' % follow_user_brief_list)
            for item in follow_user_brief_list:
                item['thumblink'] = item['imglink'][0:-1] + u'132'
                if item['userid'] in current_userid_friends_list:
                    item['type'] = 3
                elif item['userid'] in current_userid_follow_list:
                    item['type'] = 1
                elif item['userid'] in current_userid_fans_list:
                    item['type'] = 2
                else:
                    item['type'] = 0
            res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':follow_user_brief_list}
            self.write(json.dumps(res))
            self.finish()
            return

        elif current_userid is None:
            follow_userid_list = data_user_buddy_mysql.get_user_follow_by_userid(userid, begin, limit)
            if follow_userid_list is None:
                res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res': 0}
                self.write(json.dumps(res))
                self.finish()
                return
            follow_user_brief_list = data_user_brief_mysql.get_user_brief_by_userid_list(follow_userid_list)
            for item in follow_user_brief_list:
                item['thumblink'] = item['imglink'][0:-1] + u'132'
                item['type'] = 0
            res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':follow_user_brief_list}
            self.write(json.dumps(res))
            self.finish()
            return

class GetFansHandler(BaseHandler):
    @ApiGuest
    def post(self, *args, **kwargs):
        begin = self.ss_params.get('begin', None)
        limit = self.ss_params.get('limit', None)
        if begin and limit is None:
            log.i('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return
        if self.current_user:
            current_userid = self.current_user.get('userid', None)
        else:
            current_userid = None
        userid = self.ss_params.get('userid', None)
        if not userid:
            log.w('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

        current_userid_follow_list = data_user_buddy_mysql.get_user_follow_by_userid(current_userid, begin, limit)
        if current_userid_follow_list is None:
            current_userid_follow_list = []
        current_userid_fans_list = data_user_buddy_mysql.get_user_fans_by_userid(current_userid, begin, limit)
        if current_userid_fans_list is None:
            current_userid_fans_list = []
        current_userid_friends_list = list(set(current_userid_follow_list).intersection(set(current_userid_fans_list)))

        if userid is current_userid:
            if current_userid_follow_list == []:
                res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res': 0}
                self.write(json.dumps(res))
                self.finish()
                return
            current_user_fans_brief_list = data_user_brief_mysql.get_user_brief_by_userid_list(current_userid_fans_list)
            for item in current_user_fans_brief_list:
                if item['userid'] in current_userid_friends_list:
                    item['thumblink'] = item['imglink'][0:-1] + u'132'
                    item['type'] = 3
                else:
                    item['type'] = 2

            res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':current_user_fans_brief_list}
            self.write(json.dumps(res))
            self.finish()
            return

        elif userid is not current_userid:
            fans_userid_list = data_user_buddy_mysql.get_user_fans_by_userid(userid, begin, limit)
            if fans_userid_list is None:
                res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res': 0}
                self.write(json.dumps(res))
                self.finish()
                return
            fans_user_brief_list = data_user_brief_mysql.get_user_brief_by_userid_list(fans_userid_list)
            for item in fans_user_brief_list:
                item['thumblink'] = item['imglink'][0:-1] + u'132'
                if item['userid'] in current_userid_friends_list:
                    item['type'] = 3
                elif item['userid'] in current_userid_follow_list:
                    item['type'] = 1
                elif item['userid'] in current_userid_fans_list:
                    item['type'] = 2
                else:
                    item['type'] = 0
            res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':fans_user_brief_list}
            self.write(json.dumps(res))
            self.finish()
            return

        elif current_userid is None:
            fans_userid_list = data_user_buddy_mysql.get_user_fans_by_userid(userid, begin, limit)
            if fans_userid_list is None:
                res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res': 0}
                self.write(json.dumps(res))
                self.finish()
                return
            fans_user_brief_list = data_user_brief_mysql.get_user_brief_by_userid_list(fans_userid_list)
            for item in fans_user_brief_list:
                item['thumblink'] = item['imglink'][0:-1] + u'132'
                item['type'] = 0
            res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':fans_user_brief_list}
            self.write(json.dumps(res))
            self.finish()
            return

class GetBuddyCountHandler(BaseHandler):
    @ApiGuest
    def post(self, *args, **kwargs):
        userid = self.ss_params.get('userid', None)
        if not userid:
            log.w('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

        result= data_user_buddy_mysql.get_user_buddy_count_by_userid(userid)

        if result:
            res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res': result}
            self.write(json.dumps(res))
            self.finish()
            return
        else:
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

class GetSquare(BaseHandler):
    @ApiGuest
    def post(self, *args, **kwargs):

        begin = self.ss_params.get('begin', None)
        limit = self.ss_params.get('limit', None)
        if begin and limit is None:
            log.i('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return
        if self.current_user:
            current_userid = self.current_user.get('userid', None)
        else:
            square_user_brief_list = data_user_brief_mysql.get_square_users(begin, limit, [])
            for item in square_user_brief_list:
                item['thumblink'] = item['imglink'][0:-1] + u'132'
                item['type'] = 0
            res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res': square_user_brief_list}
            self.write(json.dumps(res))
            self.finish()
            return
        current_user_follow_list = data_user_buddy_mysql.get_user_follow_by_userid(current_userid, begin, limit)
        if current_user_follow_list is None:
            current_user_follow_list = []
        current_user_fans_list = data_user_buddy_mysql.get_user_fans_by_userid(current_userid, begin, limit)
        if current_user_fans_list is None:
            current_user_fans_list = []
        current_user_friends_list = list(set(current_user_follow_list).intersection(set(current_user_fans_list)))
        square_user_brief_list = data_user_brief_mysql.get_square_users(begin, limit, [current_userid])
        if square_user_brief_list is None:
            res = {'idx':self.ss_idx, 'ret':0, 'msg':'广场上暂时没有人', 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return
        for item in square_user_brief_list:
            item['thumblink'] = item['imglink'][0:-1] + u'132'
            if item['userid'] in current_user_friends_list:
                item['type'] = 3
            elif item['userid'] in current_user_follow_list:
                item['type'] = 1
            elif item['userid'] in current_user_fans_list:
                item['type'] = 2
            else:
                item['type'] = 0
        res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res': square_user_brief_list}
        self.write(json.dumps(res))
        self.finish()
        return

class GetBuddyTypeHandler(BaseHandler):
    @ApiHost
    def post(self, *args, **kwargs):
        current_userid = self.current_user.get('userid', None)
        userid = self.ss_params.get('userid', None)

        if not (current_userid and userid):
            log.w('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

        if current_userid == userid:
            log.w('user is current user')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':'user is current user', 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

        buddy_type = data_user_buddy_mysql.validate_follow_by_userid_fuserid(current_userid, userid)

        if buddy_type is None:
            log.w('buddy type is none')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

        res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':{'type': buddy_type}}
        self.write(json.dumps(res))
        self.finish()
        return

class ApiNotFindHandler( BaseHandler ) :

    def get( self ):
        raise tornado.web.HTTPError( 503 )
    @tornado.web.asynchronous
    def post( self ):
        log.i( self  )
        res = { 'idx':0, 'ret':9, 'msg':'无此功能', 'res':{} }
        self.write( json.dumps(res) )
        self.finish()